<template>
	<view class="body">
		<view class="head">
			<uni-search-bar v-model="value" @confirm="search" @input="input" ref="search" radius="18"
				cancelButton="none" placeholder="请输入搜索内容" />
		</view>
		<view v-if="value.trim().length===0" class="history">
			<view class="header">
				<text>搜索历史</text>
				<uni-icons type="trash" @click="clearHistory"></uni-icons>
			</view>
			<view class="body">
				<view class="body-item" v-for="(item,index) in historyList" :key="index" @click="clickHistory(item)">
					{{item}}
				</view>
			</view>
		</view>
		<view v-else class="searchList">
			<view class="search-item" v-for="item in searchList" :key="item.goods_id" @click="clickBtn(item)">
				<text class="text">{{item.goods_name}}</text>
				<uni-icons type="arrowright" size="17"></uni-icons>
			</view>
		</view>
	</view>


</template>

<script>
	export default {
		data() {
			return {
				value: '',
				searchList: [],
				timer: null,
				historyList:[]
			};
		},
		created() {
			this.historyList=JSON.parse(uni.getStorageSync('ygHistory')||'[]')
		},
		methods: {
			search() {			
				this.historyList.unshift(this.value)
				const arr=new Set(this.historyList)
				this.historyList=Array.from(arr)
				uni.setStorageSync('ygHistory',JSON.stringify(this.historyList))
			},
			input(value) {
				if (value.trim()==='') {
					this.searchList = []
					return
				}
			
				if (this.timer) clearTimeout(this.timer)
				this.timer = setTimeout(async () => {
					uni.showLoading({
						title:'加载中...'
					})
					const { data: { message } } = await uni.$http.get(
						`/api/public/v1/goods/qsearch?query=${value}`)
					this.searchList = message
					if(message.length===0){
						uni.showToast({
							title:'没有更多内容了...',
							icon:'error'
						})
					}else{
						uni.hideLoading()
					}
				}, 900)
			},
			clickBtn(item){
				uni.navigateTo({
					url:`/subpkg/goods_detail/goods_detail?goods_id=${item.goods_id}`
				})
			},
			clickHistory(value){
				this.value=value
			},
			clearHistory(){
				this.historyList=[]
				uni.setStorageSync('ygHistory',JSON.stringify(this.historyList))
			}
		},
	}
</script>

<style lang="scss" scoped>
	.body {
		background-color: #fcfffc;

		.head {
			height: 100rpx;
			background-color: #c01004;
		}

		.history {
			padding: 0 10rpx;
			height: 100rpx;
			line-height: 100rpx;
			border-bottom: 1px solid #f2f5f2;
			.header{
				display: flex;
				justify-content: space-between;
			}
		}

		.searchList {
			padding: 0 10rpx;

			.search-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 80rpx;
				border-bottom: 1px solid #f2f5f2;

				.text {
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

			}
		}
	}
</style>
